<?php

use app\model\Device;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Db;
use app\facade\RSA;
use think\facade\Route;
use think\facade\View;
use think\facade\Config;
use app\common\SmsDemo;
use Qcloud\Sms\SmsSingleSender;
use Qcloud\Sms\SmsMultiSender;
use Qcloud\Sms\SmsVoiceVerifyCodeSender;
use Qcloud\Sms\SmsVoicePromptSender;
use Qcloud\Sms\SmsStatusPuller;
use Qcloud\Sms\SmsMobileStatusPuller;

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
require_once __DIR__.'/function_html.php';
require_once __DIR__.'/datetime.php';
//require_once __DIR__.'/function_web.php';
$controller = Request::controller();


/**
 * @param $url
 * @param bool $path false不生成图片
 * $url = Request::instance()->domain().Route::buildUrl('web_register',['invite_code' => $id]);
$path = root_path()."public/share/{$id}.png";
$this->qrcode($url,$path);
 */
function qrcode($url, $file_url = false)
{
    require_once root_path().'/extend/phpqrcode/phpqrcode.php';
    $path = root_path() .'public/qrcode/'.$file_url;
    //(new \app\common\FileUtil())->createFile($path);
    $object = new \QRcode();
    //第二个参数false的意思是不生成图片文件，如果你写上‘picture.png’则会在根目录下生成一个png格式的图片文件
    $ret = $object->png($url, $path, 10, 20, 2);

    if($path === false){
        exit;
    }else{
        return ['path'=>$path,'url'=>\request()->domain(). '/qrcode/'.$file_url];
    }
}
/*
 * 成功提示函数
 * @param  string $msg 提示信息
 * @param  string $url 跳转地址
 * @param  integer $url 延时时间
 * @param  string $note 提示描述
 */
function win($msg, $url = '', $time = 2333, $note = "页面跳转中")
{

    $isAjax = Request::isAjax();
    if($isAjax){abort(json(['code' => 200,'message' => $msg]));}
    //返回2次
    $url = session(request()->controller().'_url');
  

    //$content = "<link rel='stylesheet' href='/static/console/sweet-alert.css'/><script src='/static/console/sweet-alert.min.js'></script><script>window.onload=myfun;countDown();function myfun(){swal('$msg','$note','success');delayURL(\"$url\",$time);document.querySelector('.confirm').onclick=function(){location.href='$url'}};function delayURL(url,time){setTimeout(\"top.location.href='\" + url + \"'\",time)}</script>";
    //$content = "<link rel='stylesheet' href='/sweet/sweet-alert.css'/><script src='__CONSOLE__/sweet/sweet-alert.min.js'></script><script>window.onload=myfun;countDown();function myfun(){swal('$msg','$note','success');delayURL(\"$url\",$time);document.querySelector('.confirm').onclick=function(){\"$url\"}};}</script>";
    $content = "<link rel='stylesheet' href='".Config::get('view.tpl_replace_string.__CONSOLE__')."/sweet/sweet-alert.css'/><script src='".Config::get('view.tpl_replace_string.__CONSOLE__')."/sweet/sweet-alert.min.js'></script><script>window.onload=myfun;countDown();function myfun(){swal('$msg','$note','success');delayURL(\"$url\",$time);document.querySelector('.confirm').onclick=function(){location.href='$url'}};function delayURL(url,time){setTimeout(\"top.location.href='\" + url + \"'\",time)}</script>";
  // halt($content);

    abort(\think\Response::create($content, 'html'));
}

function jump($msg, $url = '', $time = 2333, $note = "页面跳转中")
{

    if(strpos($url,'index.php') === false){
       // $url = 'index.php'.$url;
    }
    $isAjax = Request::isAjax();
    if($isAjax){abort(json(['code' => 200,'message' => $msg]));}
    //返回2次

    $content = "<link rel='stylesheet' href='".Config::get('view.tpl_replace_string.__CONSOLE__')."/sweet/sweet-alert.css'/><script src='".Config::get('view.tpl_replace_string.__CONSOLE__')."/sweet/sweet-alert.min.js'></script><script>window.onload=myfun;countDown();function myfun(){swal('$msg','$note','success');delayURL(\"$url\",$time);document.querySelector('.confirm').onclick=function(){location.href='$url'}};function delayURL(url,time){setTimeout(\"top.location.href='\" + url + \"'\",time)}</script>";
    //$content = "<link rel='stylesheet' href='/static/console/css/sweet-alert.css'/><script src='/static/console/js/sweet-alert.min.js'></script><script>window.onload=myfun;countDown();function myfun(){swal('$msg','$note','success');delayURL(\"$url\",$time);document.querySelector('.confirm').onclick=function(){history.go(-2)}};function delayURL(url,time){setTimeout(\"history.go(-2)\",time)}</script>";
    abort(\think\Response::create($content, 'html'));
}

/*
 * 失败提示函数
 * @param  string $msg 提示信息
 * @param  integer $time 延时时间
 * @param  string $note 提示描述
 */

function fail($msg, $time = 2333, $note = "页面跳转中")
{

    $isAjax = Request::isAjax();
    if($isAjax){abort(\think\Response::create(['code' => 400,'message' => $msg],'json'));}
    $content = "<link rel='stylesheet' href='".Config::get('view.tpl_replace_string.__CONSOLE__')."/sweet/sweet-alert.css'/><script src='".Config::get('view.tpl_replace_string.__CONSOLE__')."/sweet/sweet-alert.min.js'></script><script>window.onload=myfun;function myfun(){swal('$msg','$note','error');delayURL(3000);document.querySelector('.confirm').onclick=function(){window.history.back()}};function delayURL(time){setTimeout(\"window.history.back();\",$time)};</script>";

    abort(\think\Response::create($content, 'html'));
}

/**
 * 无层级递归
 * 递归函数后台使用 二维数据 递归树可以替代sonPath
 */
function getMenuTree($arrCat,$parent_id = 0,$field = 'parent_id',$level = 0,$str = '' )
{
    static  $arrTree = array(); //使用static代替global
    if(empty($level))
    {
        $arrTree = array(); //清空静态变量 否者递归结果会叠加
    }
    if(empty($arrCat)) return FALSE;
    $level++;

    if($parent_id == 0){
        $str .= $parent_id;
    }else{
        $str .= ','.$parent_id;
    }

    //static $i = 0;

    foreach($arrCat as $key => $value)
    {
        //$i++;
        if($value[$field] == $parent_id)
        {
            $value['level'] = $level;
            $value['current_parent_str'] = $str;
            $arrTree[] = $value;
            unset($arrCat[$key]); //注销当前节点数据，减少已无用的遍历
            getMenuTree($arrCat, $value['id'],$field = 'parent_id',$level,$str);
        }
    }
    return $arrTree;

//    array(68) {
//    [0] => array(7) {
//        ["id"] => int(2)
//        ["cat_name"] => string(3) "AAa"
//        ["parent_id"] => int(0)
//        ["status"] => int(1)
//        ["sort"] => int(1)
//        ["multi_pic"] => string(124) "a:2:{i:0;s:47:"2 / 20180707 / 9a013e5eb201b25b538e466544fcd97f . png";i:1;s:47:"2 / 20180707 / 1a532fc1abe9889760055fc266ef913c . jpg";}"
//        ["level"] => int(1)
//  }
//  [1] => array(7) {
//        ["id"] => int(26)
//        ["cat_name"] => string(12) "摄影摄像"
//        ["parent_id"] => int(2)
//        ["status"] => int(2)
//        ["sort"] => int(0)
//        ["multi_pic"] => string(0) ""
//        ["level"] => int(2)
//  }
//  }
}

/**
 * @param int $pid
 * @param int $lev
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 * 查询所有的
 */
function get_team($pid = 0, $lev = 0)
{
    $child = [];   // 定义存储子级数据数组
    $data = \think\Db::table('meminfo')->field('memphone,memname,memid,pmemid,lev,regdate')->where('pmemid', '=', $pid)->select();
    foreach ($data as $key => $value) {
        $child[] = $value['memid'];
        $child = array_merge($child, get_team($value['memid'], $lev));
    }
    return $child;
}

function myTeam($parent_id = 0, $lev = 0)
{
    $child = [];   // 定义存储子级数据数组
    $data = (new \app\model\Member())->where('parent_id', '=', $parent_id)->select()->toArray();
    foreach ($data as $key => $value) {
        $child[] = $value['id'];

        $child = array_merge($child, myTeam($value['id'], $lev));

    }
    return $child;
}


/**
 * 有层级递归
 * 多层递归前台使用
 */
function getMenuList($arr, $fid = 0,$parent_field = 'parent_id',$k = 'son')
{
    $newArr = array();
    $i = 1;
    foreach ($arr as $v) {
        if ($v[$parent_field] == $fid) {
            $v[$k] = getMenuList($arr, $v['id'],$parent_field,$k);
            $newArr[]  = $v;
            $i++;
        }
    }
    return $newArr;
//    array(55) {
//    [0] => array(7) {
//        ["id"] => int(2)
//        ["cat_name"] => string(3) "AAa"
//        ["parent_id"] => int(0)
//        ["status"] => int(1)
//        ["sort"] => int(1)
//        ["multi_pic"] => string(124) "a:2:{i:0;s:47:"2 / 20180707 / 9a013e5eb201b25b538e466544fcd97f . png";i:1;s:47:"2 / 20180707 / 1a532fc1abe9889760055fc266ef913c . jpg";}"
//        ["son"] => array(1) {
//            [0] => array(7) {
//                ["id"] => int(26)
//                ["cat_name"] => string(12) "摄影摄像"
//                ["parent_id"] => int(2)
//                ["status"] => int(2)
//                ["sort"] => int(0)
//                ["multi_pic"] => string(0) ""
//                ["son"] => array(0) {
//                }
//      }
//    }
//  }
//  [1] => array(7) {
//        ["id"] => int(4)
//        ["cat_name"] => string(33) "家居、家具、家装、厨具"
//        ["parent_id"] => int(0)
//        ["status"] => int(1)
//        ["sort"] => int(0)
//        ["multi_pic"] => string(0) ""
//        ["son"] => array(0) {
//        }
//  }
//    }
}

/**
 * 递归下级分类字符串 一维数据和分类树同理
 * @param $arrCat
 * @param int $parent_id
 * @param bool $merge 默认false不包含自己 true包含自己
 * @param bool $type 默认false返回数组 true返回字符串
 * @return array|bool|string true为字符串 false返回一维数组
 */
function sonPath($arrCat,$parent_id = 0,$merge = false,$type = false)
{
    static $arrTree = array(); //使用static代替global
    if(empty($arrCat)) return FALSE;
    static $i = 0;
    foreach($arrCat as $key => $value)
    {
        $i++;
        if($value['parent_id' ] == $parent_id)
        {
            $arrTree[] = $value['id'];
            unset($arrCat[$key]); //注销当前节点数据，减少已无用的遍历
            sonPath($arrCat, $value[ 'id']);
        }
    }
    if($merge){
        array_unshift($arrTree,$parent_id);//array_push
    }
    if($type){
        $stringTree = implode(',',$arrTree);
        return $stringTree;
    }
    //$stringTree = implode(',',$arrTree);
    return $arrTree;
    //false
//    array(1) {
//    [0] => int(26)
//}
//true    array(2) {
//    [0] => int(2)
//    [1] => int(26)
//}
}


function parentPathStatic($catId,$table = 'WebCategory')
{
    static $ret = array();//static
    $info = Db::name($table)->fetchSql(false)->field('id,parent_id,cat_name')->find($catId);
    $ret[] = $info;
    // 如果还有上级再取上级的信息
    while($info['parent_id'] > 0){
        $info = parentPath($info['parent_id'],$table);
    }
    return ($ret);
}
//function parentPathstudy($catId)
//{//最早使用这个的
//    static $ret = array();
//    $info = self::field('id,parenTid,title')->find($catId);
//    $ret[] = $info;
//    // 如果还有上级再取上级的信息
//    if($info['parenTid'] > 0)
//        $this->parentPath($info['parenTid']);
//    return $ret;
//}
/**
 * 递归上级级分类字符串
 * @param $catId
 * @param string $table
 * @return array
 */
function parentPath($cat_id,$table = 'WebCategory',$type = false){
    //没有必要合并当前数据了.上级一般只用于面包屑
    //获取当前cat_id的该条信息 循环递归
    $row = Db::name($table)->where('delete_time','=','0000-00-00 00:00:00')->find($cat_id);

    $tree = [];
    if($type){ //合并当前项
        if(!empty($row)){
            $tree[] = $row; //将该条数据放入数组中
        }

    }
    while($row['parent_id']>0){ //只要该条数据的parent_id>0
        $row = Db::name($table)->where('delete_time','=','0000-00-00 00:00:00')->find($row['parent_id']);
        $tree[] = $row;
    }
    //array_reverse();返回翻转数据的数组
    return array_reverse($tree);//翻转数据
//    array(6) {
//        [0] => array(6) {
//            ["id"] => int(22)
//            ["cat_name"] => string(9) "冰箱123"
//            ["parent_id"] => int(0)
//            ["status"] => int(1)
//            ["sort"] => int(3)
//            ["multi_pic"] => string(0) ""
//  }
//  [1] => array(6) {
//            ["id"] => int(23)
//            ["cat_name"] => string(5) "冰-1"
//            ["parent_id"] => int(22)
//            ["status"] => int(1)
//            ["sort"] => int(0)
//            ["multi_pic"] => string(0) ""
//  }
//  [2] => array(6) {
//            ["id"] => int(24)
//            ["cat_name"] => string(5) "冰02"
//            ["parent_id"] => int(23)
//            ["status"] => int(2)
//            ["sort"] => int(1)
//            ["multi_pic"] => string(0) ""
//  }}
}

/**
 * curl
 */
function https_request($url, $data = null)
{

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        $data = json_encode($data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    curl_setopt($curl, CURLOPT_HEADER, 0);

    curl_setopt($curl, CURLOPT_HTTPHEADER,

        array(

            'Content-Type: application/json; charset=utf-8',

            'Content-Length:' . strlen($data))

    );

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
function curl_post($url, array $params = array())
{

    $data_string = json_encode($params,JSON_UNESCAPED_UNICODE);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt(
        $ch, CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json'
        )
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}

function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($curl);//运行curl
    curl_close($curl);

    return $data;
}
/**
 * 加密函数
 * @param array $data
 * @param string $type
 * @return string
 */
function encryptData($data = [],$type = false,$action = false){
    return json($data);
    if($type === false){
        $type = config('app.encrypt.type');//return类型 rsa
    }
    if($action === false){
        $action = config('app.encrypt.action');//加密方式 public
    }
    if($type == 'json'){
        return json($data);
        $result_pretty = json_encode($data,JSON_PRETTY_PRINT);
        return '<pre>'.$result_pretty.'</pre>';
    }elseif($type == 'rsa'){
        if($action == 'public'){
            return (new \app\common\RSA())->publicEncrypt(json_encode($data));
        }else{
            return (new \app\common\RSA())->privateEncrypt(json_encode($data));
        }
    }elseif($type = 'html'){
        return view('',$data);
    }
}

/**
 * 自动解密函数
 * @param string $type
 * @return mixed
 */
function decryptData($action = false)
{
    $data = Request::param('key');
    if (isset($data)) {
        if($action === false){
            $action = config('app.encrypt.action');
        }
        if ($action == 'private') {
            return (new \app\common\RSA())->publicDecrypt($data);
        } else {
            return (new \app\common\RSA())->privateDecrypt($data);
        }
    } else {
        return Request::param();
    }

}

/**
 * 获取APP系统类型
 * string(109) "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
 */
function getAppType()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
        echo 'systerm is IOS';
    } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android')) {
        echo 'systerm is Android';
    } else {
        echo 'systerm is other';
    }
}

/**
 * 获取浏览器类型
 */
function getBrowserType()
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($user_agent, 'MicroMessenger') === false) {
        // 非微信浏览器禁止浏览  echo "HTTP/1.1 401 Unauthorized";
        echo '不是微信';
    } else {
        // 微信浏览器，允许访问
        echo "MicroMessenger";
        // 获取版本号
        preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $user_agent, $matches);
        echo '<br>Version:' . $matches[2];
    }
}
//PHP 获取一维或多维数组某个特定键(数组下标)的所有值
function getArrayStr(array $array, $string){
    if (!trim($string)) return false;
    preg_match_all("/\"$string\";\w{1}:(?:\d+:|)(.*?);/", serialize($array), $res);
    return $res[1];
}


/**
 * 一维数组转二维数组
 * @param $data
 * @param $title
 * @param $list
 * @return array
 */

function arrayTo2Array($data, $title, $list)
{
    if (empty($data)) return [];
    $result = [];
    $n = 0;
    foreach ($data as $key => $value) {
        $result[$n][$title] = $key;
        $result[$n][$list] = array_values($value);
        $n++;
    }
    return $result;
}

/**
 * @param $result
 * @param $arr
 * 二维数组下的以为数组合并
 */
function array2ArrayMerge($result,$arr){

    array_walk($result, function (&$value, $key, $arr) {
        //$value['start_time'] = date('Y-m-d H:i:s',time());
        //$value['end_time'] = date('Y-m-d H:i:s',time()+$value['day']*3600*24);
        $value = array_merge($value, $arr);
    }, $arr);
}


/**
 * @param array $target_arr
 * @return array
 * 二维数组取出重复值
 */
function arrayTwoUnique(array $target_arr)
{
    $result = array();
    foreach($target_arr as $key => $val){
        foreach ($val as $k => $v) {
            foreach ($result as $i => $vo) {
                if ($val[$k] == $vo[$k]) {
                    continue 3;
                }
            }
        }
        $result[] = $val;
    }
    return $result;
}


//图片保存路径
function savePicName()
{
    return $save_name = date('YmdHis') . '_' . md5(microtime(true));
}

function callback(){
    return 234;
}

/**
 *  生成缩略图和水印
 */
function thumbWater($url = 'http://app235.app.longcai.net/uploads/abc/dbd/bg.jpg',$width = 800,$height = 800,$logo = 'http://app235.app.longcai.net/uploads/logo.jpg'){


    $PHP_URL_PATH =ltrim(parse_url($url,PHP_URL_PATH)); //去除域名的地址

    if(empty($url)){
        return '';
    }
    if(!file_exists('.'.$PHP_URL_PATH)){ //有时候不好使呢
        return $PHP_URL_PATH;
    }
    $PHP_URL_PATH2 =ltrim(parse_url($logo,PHP_URL_PATH)); //去除域名的地址
    $file_url = dirname($PHP_URL_PATH);//文件夹
    $basename = basename($PHP_URL_PATH); // 文件名
    $ret_url = getcwd().$file_url.'/thumb_'.$width.'_'.$height.'_'.$basename;
    if(file_exists($ret_url)){
        if(!Config::get('app.thumb_water')){ //默认生成图片了就关闭了
            return Request::instance()->domain().$file_url.'/thumb_'.$width.'_'.$height.'_'.$basename;
        }
    }
    $image = \think\Image::open('.'.$PHP_URL_PATH);
    $image2 = $image->thumb($width,$height)->save('.'.$file_url.'/thumb_'.$width.'_'.$height.'_'.$basename);
    //$thumb_ =  $image2->water('.'.$PHP_URL_PATH2)->save('.'.$file_url.'/water_'.$basename);
    return Request::instance()->domain().$file_url.'/thumb_'.$width.'_'.$height.'_'.$basename;

}


// 多层递归
function get_cate($arr, $fid = 0)
{
    $i = 1;
    $newArr = array();
    foreach ($arr as $v) {
        if ($v["parent_id"] == $fid) {
            $newArr[] = array(
                "id"    => $v['id'],
                "pri_name" => $v['pri_name'],
                "url" => $v['url'],
                "icon" => $v['icon'],
                "son"   => get_cate($arr, $v['id']),
            );
            $i++;
        }
    }
    return $newArr;
}

/**
 * curl
 */
function http_request($url, $data = null)
{

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        $data = json_encode($data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    curl_setopt($curl, CURLOPT_HEADER, 0);

    curl_setopt($curl, CURLOPT_HTTPHEADER,

        array(

            'Content-Type: application/json; charset=utf-8',

            'Content-Length:' . strlen($data))

    );

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 抓取url内图片
 * @param $url
 * @param $saveName
 * @param $path
 * @return bool
 */
function put_file_from_url_content($url, $saveName, $path) {
    // 设置运行时间为无限制
    set_time_limit ( 0 );

    $url = trim ( $url );
    $curl = curl_init ();
    // 设置你需要抓取的URL
    curl_setopt ( $curl, CURLOPT_URL, $url );
    // 设置header
    curl_setopt ( $curl, CURLOPT_HEADER, 0 );
    // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
    // 运行cURL，请求网页
    $file = curl_exec ( $curl );
    // 关闭URL请求
    curl_close ( $curl );
    // 将文件写入获得的数据
    $filename = $path . $saveName;
    $a = $path.date('Ymd');
    mkdir($a, 0777);
    chmod($a, 0777);
    $write = @fopen ( $filename, "w" );
    if ($write == false) {
        return false;
    }
    if (fwrite ( $write, $file ) == false) {
        return false;
    }
    if (fclose ( $write ) == false) {
        return false;
    }


}

/**

 * 对查询结果集进行排序
 * @access public
 * @param array $list   查询结果
 * @param string $field 排序的字段名
 * @param array $sortBy 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array|bool
 */

function list_order($list, $field, $sortBy = 'asc')

{

    if (is_array($list)) {

        $refer = $resultSet = [];

        foreach ($list as $i => $data)

            $refer[$i] = &$data[$field];

        switch ($sortBy) {

            case 'asc': // 正向排序

                asort($refer);

                break;

            case 'desc': // 逆向排序

                arsort($refer);

                break;

            case 'nat': // 自然排序

                natcasesort($refer);

                break;

        }

        foreach ($refer as $key => $val)

            $resultSet[] = &$list[$key];



        return $resultSet;

    }



    return false;

}

/**
 * 日志写入
 * @param $data 写入内容
 */
function writeLog($data){
    $data = is_object($data) ? $data->toArray() : $data;
    $years = date('Y-m-d');
    //设置路径目录信息
    $url = root_path() .'writeLog/'.$years.'/'.request()->controller().'_'.request()->action().'.txt';

    $dir_name=dirname($url);
    //目录不存在就创建
    if(!file_exists($dir_name))
    {
        //iconv防止中文名乱码
        $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
    }
    $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
    fwrite($fp,date('Y-m-d H:i:s',time()).' '.var_export($data,true)."\r\n");//写入文件
    fclose($fp);//关闭资源通道
}

function device($device_name,$con){
    $data = is_object($data) ? $data->toArray() : $data;
    $years = date('Y-m-d');
    //设置路径目录信息
    $url = public_path() .$device_name.'.txt';

    $dir_name=dirname($url);
    //目录不存在就创建
    if(!file_exists($dir_name))
    {
        //iconv防止中文名乱码
        $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
    }
    $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
    $content = [
        'Openn'=>'开机',
        'Close'=>'关机',
        'Pause'=>'暂停',
        'BalON'=>'平衡(开)',
        'BaOFF'=>'平衡(关)',
        'OvlON'=>'超载(开)',
        'OvOFF'=>'超载(关)',
        'BalanceFault01'=>'平衡故障',
        'LimitFault02'=>'限位故障',
        'OverloadFault03'=>'超载故障',

        'MotorFault04' =>'电机故障',
        'HangUpFault05' => '挂断故障'
    ];
    if (in_array($con, ['Openn', 'Close', 'Pause'])) {

    }
    $d = ['device_name'=>$device_name,'openn'=>''];
    fwrite($fp,date('Y-m-d H:i:s',time()).' '.var_export($data,true)."\r\n");//写入文件
    fclose($fp);//关闭资源通道
}

function paylog($data)
{
    $years = date('Y-m-d');

    //设置路径目录信息
    $url = root_path() .'/paylog/'.  $years.'/'.request()->controller() . '_' . request()->action() . '.txt';
    $dir_name = dirname($url);
    //目录不存在就创建
    if (!file_exists($dir_name)) {
        //iconv防止中文名乱码
        $res = mkdir(iconv("UTF-8", "GBK", $dir_name), 0777, true);
    }
    $fp = fopen($url, "a");//打开文件资源通道 不存在则自动创建
    fwrite($fp, date('Y-m-d H:i:s', time()) . ' ' . var_export($data, true) . "\r\n");//写入文件
    fclose($fp);//关闭资源通道
}

function writeLogAlipay($text) {
    // $text=iconv("GBK", "UTF-8//IGNORE", $text);
    //$text = characet ( $text );
    file_put_contents ( dirname ( __FILE__ ).DIRECTORY_SEPARATOR."./../../log.txt", date ( "Y-m-d H:i:s" ) . "  " . $text . "\r\n", FILE_APPEND );
}

function writeLogAlipay1($text) {
    // $text=iconv("GBK", "UTF-8//IGNORE", $text);
    //$text = characet ( $text );
    file_put_contents ( "./log.txt", date ( "Y-m-d H:i:s" ) . "  " . $text . "\r\n", FILE_APPEND );
}


// 截取字符串
function strLength($str, $len=10, $etc='...')
{
    $reStr = '';
    $i = 0;
    $n = 0.0;

    //字符串的字节数
    $strlen = strlen($str);
    while(($n < $len) and ($i < $strlen))
    {
        $temp_str = substr($str, $i, 1);

        //得到字符串中第$i位字符的ASCII码
        $ascnum = ord($temp_str);

        //如果ASCII位高与252
        if($ascnum >= 252)
        {
            //根据UTF-8编码规范，将6个连续的字符计为单个字符
            $reStr = $reStr.substr($str, $i, 6);
            //实际Byte计为6
            $i = $i + 6;
            //字串长度计1
            $n++;
        }
        else if($ascnum >= 248)
        {
            $reStr = $reStr.substr($str, $i, 5);
            $i = $i + 5;
            $n++;
        }
        else if($ascnum >= 240)
        {
            $reStr = $reStr.substr($str, $i, 4);
            $i = $i + 4;
            $n++;
        }
        else if($ascnum >= 224)
        {
            $reStr = $reStr.substr($str, $i, 3);
            $i = $i + 3 ;
            $n++;
        }
        else if ($ascnum >= 192)
        {
            $reStr = $reStr.substr($str, $i, 2);
            $i = $i + 2;
            $n++;
        }
        //如果是大写字母 I除外
        else if($ascnum>=65 and $ascnum<=90 and $ascnum!=73)
        {
            $reStr = $reStr.substr($str, $i, 1);
            //实际的Byte数仍计1个
            $i = $i + 1;
            //但考虑整体美观，大写字母计成一个高位字符
            $n++;
        }
        //%,&,@,m,w 字符按1个字符宽
        else if(!(array_search($ascnum, array(37, 38, 64, 109 ,119)) === FALSE))
        {
            $reStr = $reStr.substr($str, $i, 1);
            //实际的Byte数仍计1个
            $i = $i + 1;
            //但考虑整体美观，这些字条计成一个高位字符
            $n++;
        }
        //其他情况下，包括小写字母和半角标点符号
        else
        {
            $reStr = $reStr.substr($str, $i, 1);
            //实际的Byte数计1个
            $i = $i + 1;
            //其余的小写字母和半角标点等与半个高位字符宽
            $n = $n + 0.5;
        }
    }

    //超过长度时在尾处加上省略号
    if($i < $strlen)
    {
        $reStr = $reStr.$etc;
    }

    return $reStr;
}

//隐藏字符串
function hideStr($string, $bengin = 0, $len = 4, $type = 0, $glue = "@")
{
    if (empty($string))
        return false;
    $array = array();
    if ($type == 0 || $type == 1 || $type == 4) {
        $strlen = $length = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string, 0, 1, "utf8");
            $string = mb_substr($string, 1, $strlen, "utf8");
            $strlen = mb_strlen($string);
        }
    }
    switch ($type) {
        case 1:
            $array = array_reverse($array);
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", array_reverse($array));
            break;
        case 2:
            $array = explode($glue, $string);
            $array[0] = hideStr($array[0], $bengin, $len, 1);
            $string = implode($glue, $array);
            break;
        case 3:
            $array = explode($glue, $string);
            $array[1] = hideStr($array[1], $bengin, $len, 0);
            $string = implode($glue, $array);
            break;
        case 4:
            $left = $bengin;
            $right = $len;
            $tem = array();
            for ($i = 0; $i < ($length - $right); $i++) {
                if (isset($array[$i]))
                    $tem[] = $i >= $left ? "*" : $array[$i];
            }
            $array = array_chunk(array_reverse($array), $right);
            $array = array_reverse($array[0]);
            for ($i = 0; $i < $right; $i++) {
                $tem[] = $array[$i];
            }
            $string = implode("", $tem);
            break;
        default:
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", $array);
            break;
    }
    return $string;

}




/*
 * 循环删除目录和文件
 * @param string $dir_name 目录名
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){ //检查指定的文件是否是一个目录
        if ($handle = opendir($dir_name)) {   //打开目录读取内容
            while (false !== ($item = readdir($handle))) { //读取内容
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);  //删除文件
                    }
                }
            }
            closedir($handle);  //打开一个目录，读取它的内容，然后关闭
            if (rmdir($dir_name)) { //删除空白目录
                $result = true;
            }
        }
    }
    return $result;
}

/**
 * 生成唯一字符串
 * author: xiaochuan
 * return: string
 */
function get_uniqid()
{
    return md5(uniqid(rand(), true));
}


/**
 * 生成唯一字符串
 * @param string $str
 * return string
 */
function get_uniqid2($str = '')
{
    $fileName = config('user.id'); #  不同的值（ID，分配的号码等）
    $fileName = uniqid($fileName.'_').$str;
    return $fileName;
}
//文件上传 返回/url
function uploadOne($file_field = 'single_pic',$module = 'article',$path = false)
{

//    $ret  = (new \app\common\OssTool())->upload($file_field);
//
//    return $ret['url'];


    $name = get_uniqid();
    $years = date('Y-m-d');
    $fileName = $_SERVER['DOCUMENT_ROOT'].'/storage/'.$years.'/'. $name.'.jpg' ;
    $dir_name= dirname($fileName);

    if(!file_exists($dir_name))
    {
        //iconv防止中文名乱码
        $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
    }

    move_uploaded_file($_FILES[$file_field]['tmp_name'],$fileName );
    return Request::domain().'/storage/'. $years.'/'.$name.'.jpg' ;;
    try {

        move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload/" . $_FILES["file"]["name"]);
        return  Request::domain().'/storage/'.time().'.jpg';
    } catch (Exception $e) {
    }

    if(!empty($file)){
                 $savename = \think\facade\Filesystem::disk('public')->putFile($module, $file);

                 Cache::set($file_field,Request::domain().'/storage/'.$savename);
//                 $ret  = (new \app\common\OssTool())->upload('file');
//                 return $ret['url'];
                 if($path == true){
                    return public_path().'public/storage/'.$savename;
                 }else{
                     return  Request::domain().'/storage/'.$savename;
                 }

             }
}
function uploadOneOrigin($file_field = 'single_pic',$module = 'article',$name = false)
{
    $file = request()->file($file_field);
    if(!empty($file)){
        $savename = \think\facade\Filesystem::disk('public')->putFileAs($module, $file,$file->getOriginalName());
        Cache::set($file_field,Request::domain().'/storage/'.$savename);
        return  Request::domain().'/storage/'.$savename;
    }
}


/**
 * @param $base64_image_content
 * @param $path
 * @return bool|string 把base64图片保存在指定目录内
 */
function base64ImageDownload($base64_image_content,$path){

    //base64ImageDownload($content,'base64/');
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){

        //        array(3) {
        //            [0] => string(22) "data:image/png;base64,"
        //            [1] => string(22) "data:image/png;base64,"
        //            [2] => string(3) "png"
        //}
        $type = $result[2]; //图片类型png
        $new_file = $path;
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.uniqid().".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            //return '/'.$new_file;
            return $new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
/**
 * 抓取网页图片并且保存
 * @param string $url 抓取URL
 * @param string $save_path 保存路径
 * @param $save_name 保存名称
 * @param bool $show_image 是否浏览器输出图片
 */
function downloadUrlImage($url = 'https://avatar.csdn.net/A/E/3/3_qq_38256963.jpg', $save_path = './uploads/member/',$save_name = 12,$show_image = false)
{
    $img = file_get_contents($url, true);
    //使用图片头输出浏览器
    if(!file_exists($save_path)){
        //检查是否有该文件夹，如果没有就创建，并给予最高权限
        mkdir($save_path, 0700);
    }
    $save_url = $save_path.$save_name.'.png';
    file_put_contents($save_url, $img);
    header("Content-Type: image/jpeg;text/html; charset=utf-8");
    if($show_image === true){
        echo $img;
        exit;
    }

}

function mails($x = '765101137@qq.com')
{

    //设置邮件发送的时间，如果不设置，则会显示其他区的时间
    require_once '../extend/PHPMailer/src/PHPMailer.php';
    require_once '../extend/PHPMailer/src/SMTP.php';
    date_default_timezone_set('PRC');
    $mail = new \PHPMailer();
    //是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
    $mail->SMTPDebug = 0;

    //使用smtp鉴权方式发送邮件，当然你可以选择pop方式 sendmail方式等 本文不做详解
    //可以参考http://phpmailer.github.io/PHPMailer/当中的详细介绍
    $mail->isSMTP();

    //smtp需要鉴权 这个必须是true
    $mail->SMTPAuth=true;

    //链接qq域名邮箱的服务器地址
    $mail->Host = 'smtp.qq.com';

    //设置使用ssl加密方式登录鉴权
    $mail->SMTPSecure = 'ssl';

    //设置ssl连接smtp服务器的远程服务器端口号 可选465或587
    $mail->Port = 465;

    //设置发件人的主机域 可有可无 默认为localhost 内容任意，建议使用你的域名,这里为默认localhost
    $mail->Hostname = 'http://shishurong.com';

    //设置发送的邮件的编码 可选GB2312
    $mail->CharSet = 'UTF-8';
    // ulrkfwxdyyeleaba
    //设置发件人姓名（昵称）可为任意内容，不影响回复(设置为qq昵称即可)
    $mail->FromName = '顶级购物商城';

    //smtp登录的账号 这里填入qq号即可
    $mail->Username ='2355308574';

    //smtp登录的密码 这里填入“独立密码” 若为设置“独立密码”则填入登录qq的密码 建议设置“独立密码”
    $mail->Password = 'dfdjyvwokauxeaed';

    //设置发件人邮箱地址 这里填入上述提到的“发件人邮箱”

    $mail->From = '2355308574@qq.com';

    //邮件正文是否以html方式发送
    $mail->isHTML(true);

    //设置收件人邮箱地址 该方法有两个参数 第一个参数为收件人邮箱地址 第二参数为给该地址设置的昵称 不同的邮箱系统会自动进行处理变动 这里第二个参数的意义不大

    $mail->addAddress($x,'');

    //可添加多个收件人
    //$mail->addAddress('XXXX@qq.com','XXXXX');

    //添加该邮件的主题
    $mail->Subject = '这是一个PHPMailer发送邮件的示例';

    //添加邮件正文
    $mail->Body = "这是一个<b style=\"color:red;\">PHPMailer</b>发送邮件的一个测试用例";

    //为该邮件添加附件 该方法也有两个参数 第一个参数为附件存放的目录（相对目录、或绝对目录均可）
    //第二参数为在邮件附件中该附件的名称
    // $mail->addAttachment('./src/20151002.png','test.png');

    //同样该方法可以多次调用 上传多个附件
    //$mail->addAttachment('./Jlib-1.1.0.js','Jlib.js');

    //发送命令 返回布尔值
    //PS：经过测试，要是收件人不存在.若不出现错误依然返回true也就是说在发送之前
    //自己需要些方法实现检测该邮箱是否真实有效
    $status = $mail->send();
    halt($status);
    //简单的判断与提示信息
    if($status)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function getDistance($lat1, $lng1, $lat2, $lng2){

    // 将角度转为狐度
    $radLat1 = deg2rad($lat1);// deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2)+cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return $s;

}

/**
 * @return string 8位随机字符串
 */
function x()
{
    return sprintf('%x', crc32(microtime()));
}

/**
 * 随机字符串
 */
function randStr($length = 8)
{
    // 密码字符集，可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符；
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}

function randNum($length = 8)
{
    // 密码字符集，可任意添加你需要的字符
    $chars = '12345667890';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符；
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}



/**
 * PHP判断用户访问的操作系统,以及iOS的设备
 * @return string
 */
function getOS()
{
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);

    if (strpos($agent, 'windows nt')) {
        $platform = 'windows';
    } elseif (strpos($agent, 'macintosh')) {
        $platform = 'mac';
    } elseif (strpos($agent, 'ipod')) {
        $platform = 'ipod';
    } elseif (strpos($agent, 'ipad')) {
        $platform = 'ipad';
    } elseif (strpos($agent, 'iphone')) {
        $platform = 'iphone';
    } elseif (strpos($agent, 'android')) {
        $platform = 'android';
    } elseif (strpos($agent, 'unix')) {
        $platform = 'unix';
    } elseif (strpos($agent, 'linux')) {
        $platform = 'linux';
    } else {
        $platform = 'other';
    }
    return $platform;
}


function curl($url, $data = NULL, $json = false,$headers = [])

{

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    if (!empty($data)) {

        if ($json && is_array($data)) {

            $data = json_encode($data);
        }

        curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        if ($json) { //发送JSON数据

            curl_setopt($curl, CURLOPT_HEADER, 0);

            curl_setopt($curl, CURLOPT_HTTPHEADER,

                array(

                    'Content-Type: application/json; charset=utf-8',

                    'Content-Length:' . strlen($data))

            );

        }

    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $res = curl_exec($curl);

    $errorno = curl_errno($curl);


    if ($errorno) {

        return array('errorno' => false, 'errmsg' => $errorno);

    }

    curl_close($curl);

    return json_decode($res, true);

}


///**
// * 使用3DES加密源数据
// * @param string $oriSource 源数
// * @param string $key 密钥
// * @param string $defaultIV 加解密向量
// * @return string $result   密文
// */
//function encryptdata($oriSource)
//{
//    $oriSource = addPKCS7Padding($oriSource);
//    $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
//    mcrypt_generic_init($td, '123456781234567812345678', '12345678');
//    $result = mcrypt_generic($td, $oriSource);
//    $result = base64_encode($result);
//    mcrypt_generic_deinit($td);
//    mcrypt_module_close($td);
//    return $result;
//}
//
//
///**
// * 使用3DES解密密文
// * @param string $encryptedData 密文
// * @param string $key 密钥
// * @param string $defaultIV 加解密向量
// * @return string $result       解密后的原文
// */
//function decrypt_des($encryptedData)
//{
//
//    $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
//    mcrypt_generic_init($td, '123456781234567812345678', '12345678');
//
//    $encryptedData = base64_decode($encryptedData);
//    $result = mdecrypt_generic($td, $encryptedData);
//
//    mcrypt_generic_deinit($td);
//    mcrypt_module_close($td);
//    $result = stripPKSC7Padding($result);
//    return $result;
//}
function AgoTime($datatime){
    $now_time = time();
    $create_time = strtotime($datatime);
    $after_time = $now_time - $create_time;

    if($after_time < 60){
        return $after_time .'秒前';
    }
    if($after_time >= 60 && $after_time <= 3600){ //一个小时内
        return floor($after_time/60).'分钟前';
    }
    if($after_time > 3600 && $after_time < 3600*24){ //一天内
        return floor($after_time/60/60).'小时前';
    }
    if($after_time > 3600*24 && $after_time < 3600*24*30){
        return floor($after_time/60/60/24).'天前';
    }
    if($after_time > 3600*24*30 && $after_time < 3600*24*30*365){
        return floor($after_time/60/60/24/30).'个月前';
    }
    if($after_time > 3600*24*30*365){
        return floor($after_time/60/60/24/30/365).'年前';
    }

    return $datatime;
}

function formatDate($time) {
    if (preg_match('/\d{1,4}[^\d]+\d{1,2}[^\d]+\d{1,2}(\s+\d{1,2}[^\d]+\d{1,2}[^\d]+\d{1,2})?/', $time)) {
        $time = strtotime($time);
    }
    $t = time() - $time;
    $f = array(
        '31536000' => '年',
        '2592000'  => '个月',
        '604800'   => '星期',
        '86400'    => '天',
        '3600'     => '小时',
        '60'       => '分钟',
        '1'        => '秒',
    );
    $qh = $t > 0 ? '前' : '后';
    $t  = abs($t);
    foreach ($f as $k => $v) {
        if (0 != ($c = floor($t / (int) $k))) {
            return abs($c) . $v . $qh;
        }
    }
}

/**
 * 获取两个日期之间相隔的年、月、日、时、分、秒
 * @param $startDateTime
 * @param $endDateTime
 * @return array
 */
function timeDiff($startDateTime, $endDateTime) {
    $startDateTime = new DateTime($startDateTime);
    $endDateTime = new DateTime($endDateTime);
    $interval = $startDateTime->diff($endDateTime);
    $formatMap = [
        'y' => 'year',
        'm' => 'month',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
        'days' => 'days',
    ];
    $returnData = [];
    foreach ($formatMap as $key => $val) {
        $returnData[$val] = $interval->{$key};
    }
    return $returnData;
}


/**
 * NULL 转换成 ''
 *
 */
function unsetNull($arr){
    if($arr !== null){
        if(is_array($arr)){
            if(!empty($arr)){
                foreach($arr as $key => $value){
                    if($value === null){
                        $arr[$key] = '';
                    }else{
                        $arr[$key] = unsetNull($value);      //递归再去执行
                    }
                }
            }else{ $arr = ''; }
        }else{
            if($arr === null){ $arr = ''; }         //注意三个等号
        }
    }else{ $arr = ''; }
    return $arr;
}

/**
 * 获取中文首字母
 * @param $str
 * @return string
 */
function getFirstChar($str) {
    if (empty($str)) {
        return '';
    }

    $fir = $fchar = ord($str[0]);
    if ($fchar >= ord('A') && $fchar <= ord('z')) {
        return strtoupper($str[0]);
    }

    $s1 = @iconv('UTF-8', 'gb2312//IGNORE', $str);
    $s2 = @iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    if (!isset($s[0]) || !isset($s[1])) {
        return '';
    }

    $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;

    if (is_numeric($str)) {
        return $str;
    }

    if (($asc >= -20319 && $asc <= -20284) || $fir == 'A') {
        return 'A';
    }
    if (($asc >= -20283 && $asc <= -19776) || $fir == 'B') {
        return 'B';
    }
    if (($asc >= -19775 && $asc <= -19219) || $fir == 'C') {
        return 'C';
    }
    if (($asc >= -19218 && $asc <= -18711) || $fir == 'D') {
        return 'D';
    }
    if (($asc >= -18710 && $asc <= -18527) || $fir == 'E') {
        return 'E';
    }
    if (($asc >= -18526 && $asc <= -18240) || $fir == 'F') {
        return 'F';
    }
    if (($asc >= -18239 && $asc <= -17923) || $fir == 'G') {
        return 'G';
    }
    if (($asc >= -17922 && $asc <= -17418) || $fir == 'H') {
        return 'H';
    }
    if (($asc >= -17417 && $asc <= -16475) || $fir == 'J') {
        return 'J';
    }
    if (($asc >= -16474 && $asc <= -16213) || $fir == 'K') {
        return 'K';
    }
    if (($asc >= -16212 && $asc <= -15641) || $fir == 'L') {
        return 'L';
    }
    if (($asc >= -15640 && $asc <= -15166) || $fir == 'M') {
        return 'M';
    }
    if (($asc >= -15165 && $asc <= -14923) || $fir == 'N') {
        return 'N';
    }
    if (($asc >= -14922 && $asc <= -14915) || $fir == 'O') {
        return 'O';
    }
    if (($asc >= -14914 && $asc <= -14631) || $fir == 'P') {
        return 'P';
    }
    if (($asc >= -14630 && $asc <= -14150) || $fir == 'Q') {
        return 'Q';
    }
    if (($asc >= -14149 && $asc <= -14091) || $fir == 'R') {
        return 'R';
    }
    if (($asc >= -14090 && $asc <= -13319) || $fir == 'S') {
        return 'S';
    }
    if (($asc >= -13318 && $asc <= -12839) || $fir == 'T') {
        return 'T';
    }
    if (($asc >= -12838 && $asc <= -12557) || $fir == 'W') {
        return 'W';
    }
    if (($asc >= -12556 && $asc <= -11848) || $fir == 'X') {
        return 'X';
    }
    if (($asc >= -11847 && $asc <= -11056) || $fir == 'Y') {
        return 'Y';
    }
    if (($asc >= -11055 && $asc <= -10247) || $fir == 'Z') {
        return 'Z';
    }

    return '';
}

/**
 * @param $path
 * @param bool $fileurl
 * @return array
 * 获取文件夹后者文件
 */
function getDirFile($path,$fileurl = false){
    $list = [];
    $data = '';
    $temp_list = scandir($path);
    $i = 0;
    foreach ($temp_list as $file){
        if ($file != ".." && $file != "."){
            if (is_dir($path . "/" . $file)){

                if($fileurl){
                    $d = getDirFile($path . "/" . $file,$fileurl);
                    $i++;
                    for ($a=0;$a<count($d);$a++){
                        $list[] = $d[$a]; //'./'. 第一次文件加不上
                    }
                }else{
                //子文件夹，进行递归
                    $list[][$file] = getDirFile($path . "/" . $file);
                }




            }else{
                if($fileurl){
                    $list[] = $path.'/'.$file;
                }else{
                    $list[] = $file;
                    //根目录下的文件
                }


                //$list['data'][] = $file;
            }

        }
    }
    return $list;
}

/**
 * @param $array
 * @param $index
 * @param $value
 * @return string
 * 根据二维数据查询指定数据
 */
function filter_by_value($array, $index, $value)
{
    $newarray = '';
    if (is_array($array) && count($array) > 0) {
        foreach (array_keys($array) as $key) {
            $temp[$key] = $array[$key][$index];
            if ($temp[$key] == $value) {
                $newarray[$key] = $array[$key];
            }
        }
    }
    return $newarray;
}

//PHP 二维数组 根据一个值或者多个值来去重
function remove_duplicate($array)
{
    $result = array ();
    foreach ($array as $key => $value) {
        $has = false;
        foreach ($result as $val) {
            if ($val['code'] == $value['code']) {
                $has = true;
                break;
            }
        }
        if (!$has)
            $result[] = $value;
    }
    return $result;
}

function gen(){
    $ret = [];
    for ($i =0;$i<=1000;$i++){
        yield [$i,rand(1,10000)];
        $ret[] = $i;
    }
   // return $ret;
}

/*
 * 删除空格和回车
 */
function trimSpacheEnter($str)
{
    $str = strip_tags($str);
    $qian = array(" ", "　", "\t", "\n", "\r");
    return str_replace($qian, '', $str);
}

/**
 * @param $zfc
 * @return false|int
 * 查看字符串长度
 */
function Length($zfc){
    $arr = [];
    $len = mb_strlen($zfc);
    for ($i = 0; $i < $len; $i++) {
        array_push($arr,$zfc[$i]);
    }
    //字符串长度
    $len = count($arr);
    return $len;
}

function year($start){
    $year = [];
    $now_year = date('Y',time());
    for($i=$start;$i>=0;$i--){
        $year[] = $now_year-$i;
    }
    $year = array_reverse($year);
    return $year;
}

//跟输入的时候保持一致
function textArea($string)
{
    return nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($string, ENT_QUOTES)));
}


//将换行的字符串变成数组
function textAreaArray($string)
{
    $list = explode("\n", $string);
    $list = array_map("trim", $list);
    return array_unique(array_filter($list));
}

/** 这个不可以直接使用 + 等特殊符号没有处理
 * des-ecb加密
 * @param string $data 要被加密的数据
 * @param string $key 加密密钥(64位的字符串)
 */
function des_encrypt($data, $key){
     $data = openssl_encrypt($data, 'des-ecb', $key);
     return $data = str_replace(array('/', '+'), array('_', '-'), $data);
}

/**
 * des-ecb解密
 * @param string $data 加密数据
 * @param string $key 加密密钥
 */
function des_decrypt($data, $key){
    $data = str_replace(array('_', '-'), array('/', '+'), $data);
    return openssl_decrypt($data, 'des-ecb', $key);
}

///**
// * 使用3DES加密源数据
// * @param string $oriSource 源数
// * @param string $key 密钥
// * @param string $defaultIV 加解密向量
// * @return string $result   密文
//附录：php7 des加密解密
//
//以下内容转自：https://blog.csdn.net/qq_35979073/article/details/81449590

//1.在linux 环境中如果没有装encrypt扩展 或者php版本大于7.1不支持encrypt加密扩展
// */
//function encrypt($oriSource)
//{
//    $oriSource = addPKCS7Padding($oriSource);
//    $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
//    mcrypt_generic_init($td, '123456781234567812345678', '12345678');
//    $result = mcrypt_generic($td, $oriSource);
//    $result = base64_encode($result);
//    mcrypt_generic_deinit($td);
//    mcrypt_module_close($td);
//    return $result;
//}
//
//
///**
// * 使用3DES解密密文
// * @param string $encryptedData 密文
// * @param string $key 密钥
// * @param string $defaultIV 加解密向量
// * @return string $result       解密后的原文
// */
//function decrypt($encryptedData)
//{
//
//    $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
//    mcrypt_generic_init($td, '123456781234567812345678', '12345678');
//
//    $encryptedData = base64_decode($encryptedData);
//    $result = mdecrypt_generic($td, $encryptedData);
//
//    mcrypt_generic_deinit($td);
//    mcrypt_module_close($td);
//    $result = stripPKSC7Padding($result);
//    return $result;
//}

function order_number()
{
    //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
    $order_id_main = date('YmdHis') . rand(10000000, 99999999);
    //订单号码主体长度
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
        $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

    return $order_id;
}

/*
 * 生成店铺订单号码
 */
function shop_order_number($shop_id)
{
    return date('YmdHis', time())
        . mt_rand(10, 99)
        . sprintf('%010d', time() - 946656000)
        . sprintf('%03d', (float)microtime() * 1000)
        . sprintf('%03d', (int)$shop_id % 1000);
}
/**
 * 模拟tab产生空格
 * @param int $step
 * @param string $string
 * @param int $size
 * @return string
 */
function tab($step = 1, $string = ' ', $size = 4)
{
    return str_repeat($string, $size * $step);
}

function debx()
{
    $dkm   = 12; //贷款月数，20年就是240个月
    $dkTotal = 400000; //贷款总额
    $dknl  = 0.0515; //贷款年利率
    $emTotal = $dkTotal * $dknl / 12 * pow(1 + $dknl / 12, $dkm) / (pow(1 + $dknl / 12, $dkm) - 1); //每月还款金额
    $lxTotal = 0; //总利息
    for ($i = 0; $i < $dkm; $i++) {
        $lx   = $dkTotal * $dknl / 12;  //每月还款利息
        $em   = $emTotal - $lx; //每月还款本金
        echo "第" . ($i + 1) . "期", " 本金:", $em, " 利息:" . $lx, " 总额:" . $emTotal, "<br />";
        $dkTotal = $dkTotal - $em;
        $lxTotal = $lxTotal + $lx;
    }
    echo "总利息:" . $lxTotal;
}


function debj()
{
    $dkm   = 360; //贷款月数，20年就是240个月
    $dkTotal = 400000; //贷款总额
    $dknl  = 0.0515; //贷款年利率

    $em   = $dkTotal / $dkm; //每个月还款本金
    $lxTotal = 0; //总利息
    for ($i = 0; $i < $dkm; $i++) {
        $lx   = $dkTotal * $dknl / 12; //每月还款利息
        echo "第" . ($i + 1) . "期", " 本金:", $em, " 利息:" . $lx, " 总额:" . ($em + $lx), "<br />";
        $dkTotal -= $em;
        $lxTotal = $lxTotal + $lx;
    }
    echo "总利息:" . $lxTotal;
}

function price($num)
{
    if ($num == 0) {
        return "0.00";
    }
    return number_format($num, 2, '.', '');
}



function sendSMS($phone, $content)
{
    $yourAccessKeyId  = "LTAI5tEkKio55srdHRQ8i7KM";
    $yourAccessKeySecret = "m2ct9QopU0s9X0mVErAVBCSypXGz92";
    $sms = new SmsDemo($yourAccessKeyId, $yourAccessKeySecret);

    $signName = "绿润丰达";
    $templateCode = "SMS_232810163";
    $code = array(
        "code"=> $content,
    );

    $response = $sms->sendSms($signName,$templateCode,$phone,$code);

    return $response;
}

/*
 * utf8转gbk
 */
function utf8_gbk($str)
{
    return iconv("UTF-8", "gbk//TRANSLIT", $str); //将字符串的编码从UTF-8转到GB2312
}
/*
 * gbk转utf8
 */
function gbk_utf8($str)
{
    return iconv('GB2312', 'UTF-8', $str); //将字符串的编码从UTF-8转到GB2312
}


function update_domain($model,$search = 'https://beikerui.cn')
{
    $data = model($model)->select();

    foreach ($data as $v) {

//        $multi_pic = $v['multi_pic'];
        $multi_pic = [];
        if(!empty($v['multi_pic'])){
            foreach ($v['multi_pic'] as $v2){
                $multi_pic[] = ['img'=>str_replace($search,\request()->domain(),$v2['img']),'info'=>'','show'=>''];
            }
        }

        model($model)->where('id',$v['id'])->update(['single_pic' => str_replace($search, \request()->domain(), $v['single_pic']),'multi_pic'=>serialize($multi_pic)]);
    }
}
function update_member($model,$search = 'https://beikerui.cn')
{
    $data = model($model)->select();

    foreach ($data as $v) {

//        $multi_pic = $v['multi_pic'];
//        $multi_pic = [];
//        if(!empty($v['headimgurl'])){
//            foreach ($v['multi_pic'] as $v2){
//                $multi_pic[] = ['img'=>str_replace($search,\request()->domain(),$v2['img']),'info'=>'','show'=>''];
//            }
//        }

        model($model)->where('id',$v['id'])->update(['headimgurl' => str_replace($search, \request()->domain(), $v['headimgurl'])]);
    }
}























